package tuvienna.jade.participant;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import tuvienna.jade.Constants;
import tuvienna.jade.InterestSet;

/**
 * Receive a knowledge update from a table and update the knowledge for the 
 * interest of a participant.
 * 
 */
public class DiscussionParticipationBehavior extends CyclicBehaviour {

	private static final long serialVersionUID = 1021611849811542532L;

	ParticipantAgent participant;
	long lastChange = -1;
	private MessageTemplate mt;

	public DiscussionParticipationBehavior(ParticipantAgent participant) {
		super();
		this.participant = participant;
		mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
				MessageTemplate.MatchConversationId(Constants.KNOWLEDGE_SHARED));
	}

	public void action() {
		ACLMessage msg = participant.receive(mt);
		if (msg != null)
			try {
				InterestSet	content = (InterestSet) msg.getContentObject();
				// discard "old" msg, only accept for current table
				if (msg.getSender().equals(participant.getTable())) { 
					participant.updateDiscussionTopic(content);
				}
			} catch (UnreadableException e) {
				e.printStackTrace();
			}
		 else {
			block();
		}
	}

}
